package br.com.andre.neo4j.model;

import org.neo4j.cypher.internal.mutation.Traverse;
import org.neo4j.graphdb.Direction;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Path;
import org.neo4j.graphdb.index.Index;
import org.neo4j.graphdb.traversal.Evaluators;
import org.neo4j.graphdb.traversal.TraversalDescription;
import org.neo4j.graphdb.traversal.Traverser;
import org.neo4j.kernel.Traversal;

public class TestTraversal {
	private Connection conn;
	public TestTraversal() {
		this.conn = new Connection();
	}
	
	public void getMoviesActor(final ActorTO actor) {
		int numberMovies = 0;
		GraphDatabaseService graph = conn.newConnection();
		Traverser traverser = null;
		Node node = getNodeActor(actor, graph);
		if (node != null) {
			TraversalDescription td = Traversal.description()
					.breadthFirst()
					.relationships(RelType.SERVED, Direction.OUTGOING)
					.evaluator(Evaluators.excludeStartPosition());
			traverser = td.traverse(node);	
		}
		for (Path movies : traverser) {
			System.out.println("Depth: " + movies.length());
			System.out.println("Node:" + movies.endNode().getProperty("title"));
			numberMovies++;
		}
		System.out.println("Number Movies "+ numberMovies);
		graph.shutdown();
	}

	private Node getNodeActor( ActorTO actor, GraphDatabaseService graph) {
		Index<Node> index = graph.index().forNodes("actor");
		Node node = index.get("name", actor.getName()).getSingle();
		return node;
	}
	
	public void getActorsThisMovie(UserTO user){
		int numberActors = 0;
		GraphDatabaseService graph = conn.newConnection();
		Traverser traverser = null;
		Node node =  getNodeUser(user, graph);
		if (node != null) {
			TraversalDescription td = Traversal.description()
					.depthFirst()
					.relationships(RelType.WATCHED, Direction.OUTGOING)
					.relationships(RelType.SERVED, Direction.INCOMING)
					.evaluator(Evaluators.includeWhereLastRelationshipTypeIs(RelType.SERVED));
			traverser = td.traverse(node);
		}
		for (Path actors : traverser) {
			System.out.println("Depth: " + actors.length());
			System.out.println("Node:" + actors.endNode().getProperty("name"));
			numberActors++;
		}
		System.out.println("Number Actors "+ numberActors);
		graph.shutdown();
	}

	private Node getNodeUser(UserTO user, GraphDatabaseService graph) {
		Index<Node> index = graph.index().forNodes("user");
		Node node = index.get("login", user.getLogin()).getSingle();
		return node;
	}
}
